import React, { useState }from 'react';
import { Row, Flex, Modal, InputNumber, Progress, Button, Tooltip } from 'antd';
import {
  FieldTimeOutlined,
  DollarOutlined,
  LogoutOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import { API_HOST } from './Util.jsx'

function getCurrentUserId() {
  let userInfo = JSON.parse(localStorage.getItem('card_player'))
  return userInfo.id
}


const ActionDialog = ({game}) => {

  const [amount, setAmount] = useState(game.MinAmount);
  const showModal = () => {
    // 下注阶段；当前用户，且当前用户没有弃牌
    return (getCurrentUserId() == game.Players[game.CurrPlayer].Id) && 
            (game.Players[game.CurrPlayer].HasFold == false) &&
            (game.State == "PLAYING")
  };

  const handleOk = () => {
    axios.post(API_HOST()+"/api/play/action", {
      "roomId": game.RoomId,
      "gameId": game.Id,
      "playerId": getCurrentUserId(),
      "amount": amount
    })
  };

  const handleFold = () => {
    axios.post(API_HOST()+"/api/play/action", {
      "roomId": game.RoomId,
      "gameId": game.Id,
      "playerId": getCurrentUserId(),
      "amount": -1
    })
  }

  return (<>
  <Modal title="轮到你下注了，倒计时" open={showModal()} onOk={handleOk} footer={null} closable={false}>
    <Progress percent={game.Players[game.CurrPlayer].Timeout} showInfo={false} />
    <InputNumber min={game.MinAmount} max={100} defaultValue={game.MinAmount} onChange={(v)=>setAmount(v)}/>
    <Button onClick={handleOk} type="primary">下注</Button>
    <Button onClick={handleFold} type="primary" danger>弃牌</Button>

  </Modal>
  </>)
}

const doAnte = (game, choice) => {
  axios.post(API_HOST()+"/api/play/choose", {
    "roomId": game.RoomId,
    "gameId": game.Id,
    "playerId": getCurrentUserId(),
    "choice": choice
})
} 

const IsPlayer = (game, id) =>{
    for (let i=0; i< game.Players.length; i++) {
      if (game.Players[i].Id == id) {
        return true
      }

    }
    return false
}

const AnteCell = ({game, idx}) => {

    if (game.State == "END") {
      return <p>手牌：{game.Players[idx].Card}</p> 
    }

    if (game.State == "PLAYING") {
      if (game.Players[idx].Id == getCurrentUserId()) {
        return (
          <p>手牌：{game.Players[idx].Card}</p> 
        )
      }
      else if (game.Players[idx].IsHuman == false && !IsPlayer(game, getCurrentUserId())) {
        // 利益不相关（当前玩家不在游戏中，可以查看AI的手牌）
        return (
          <p>手牌：{game.Players[idx].Card}</p> 
        )

      }
      else {
        return (
          <p>手牌：？？？</p> 
        )

      }
    }

    else if (game.State == "NEWGAME") {
      if (game.Players[idx].Ante > 0){
        return <p>底注：{game.Players[idx].Ante}</p>
      }
      else {
        if (game.Players[idx].Id == getCurrentUserId())
          return (
          <>
            <Button onClick={()=>doAnte(game, 'ante')} type="primary">下底注 {game.Players[idx].Timeout}</Button>
            <Button onClick={()=>doAnte(game, 'leave')} type="primary" danger>离场</Button>
          </>
          )
        else
          return <div>-</div>
      }
    }

    else {
      if (game.Players[idx].HasQuit) {
        return <p>已离场</p>
      }
      else {
        return <p>-</p>
      }
          
    }

}

const ActionCell = ({item}) => {

  if (!item) {
    return <div>&nbsp;</div>
  }

  if (item.Action == "WAIT") {
    return <div><FieldTimeOutlined /></div>
  }

  if (item.Action == "BET") {
    let title = <span>{item.Comment.split("\n").map((x) => <p>{x}</p>)}</span>
    return <div><Tooltip title={title}>{item.Bet}</Tooltip></div>
  }

  if (item.Action == "FOLD") {
    let title = <span>{item.Comment.split("\n").map((x) => <p>{x}</p>)}</span>
    return <div><Tooltip title={title}>X</Tooltip></div>
  }

  if (item.Action == "SKIP") {
    return <div>-</div>
  }

  return <div>-</div>
}

const Play = ({game}) => {
    
    // console.log(game)

    // 把Record记录按人数分行（显示）
    let recordArray = game.Records

    if (game.State == "PLAYING") {
      // 下注过程中，绘制等待下注图标；其它状态下不显示
      recordArray.push({
        PlayerId: game.Players[game.CurrPlayer].Id,
        Action: "WAIT",
      })
    }

    // console.log(recordArray)
    let n = game.Players.length

    var rowsArray = [];
    var length = recordArray.length;
    var index = 0;
  
    while (index < length) {
      rowsArray.push(recordArray.slice(index, index + n));
      index += n;
    }
  
    if (length>0) {
      // 补齐最后一行
      var lastRow = rowsArray[rowsArray.length - 1];
      var lastRowLength = lastRow.length;
    
      if (lastRowLength < n) {
        var padding = n - lastRowLength;
        for (var i = 0; i < padding; i++) {
          lastRow.push(null);
        }
      }
    }

    return (
      <>

      <Row>
        <Flex style={{"width": "100%", "color": "red"}} justify="space-around" >
          <div>
            {game.State}
          </div>

          <div>
            奖池{game.PrizePool}
          </div>
        </Flex>
      </Row>

      <Row >
        <Flex style={{"width": "100%"}} justify="space-around">
          {game.Players.map((x, idx)=> <div key={idx}> <p>{x.Name}</p> <p>筹码：{x.Chips}/{x.Profit-x.Invest}</p>  </div> )}
        </Flex>
      </Row>

      <Row>
        <Flex style={{"width": "100%"}} justify="space-around">
          {game.Players.map((x, idx)=> <div key={idx}><AnteCell game={game} idx={idx} /></div>)}
        </Flex>
      </Row>

      {
        rowsArray.map((row, rowIndex) => <Row key={rowIndex}>
          <Flex style={{"width": "100%"}} justify="space-around">
            {
              row.map((item, idx) => <div key={idx}><ActionCell item={item}/></div>)
            }
          </Flex>
        </Row>)
      }

      <ActionDialog game={game}/>
      </>
  
    )

}

export default Play;
